package com.tian.controller;


import com.tian.pojo.Users;
import com.tian.pojo.vo.UsersVO;
import com.tian.resourse.FileResource;
import com.tian.service.FdfsService;
import com.tian.service.center.CenterUserService;
import com.tian.utils.CookieUtils;
import com.tian.utils.JSONResult;
import com.tian.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("fdfs")
public class CenterUserController  extends BaseController{

    @Autowired
    private FileResource fileResource;

    @Autowired
    private CenterUserService centerUserService;

    @Autowired
    private FdfsService fdfsService;


    @PostMapping("uploadFace")
    public JSONResult uploadFace(
            String userId,
            MultipartFile file,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception{

        String path ="";
        //开始文件上传
        if (file !=null){
            //获得文件上传的文件名称
            String filename = file.getOriginalFilename();
            if (StringUtils.isNotBlank(filename)){
                //文件重命名 tian-face.png - > ["tian-face","png"]
                String[] fileNameArr = filename.split("\\.");
                //获取文件的后缀名
                String suffix = fileNameArr[fileNameArr.length - 1];

                if (!suffix.equalsIgnoreCase("png")&&
                        !suffix.equalsIgnoreCase("jpg")&&
                        !suffix.equalsIgnoreCase("jpeg")){
                    return JSONResult.errorMsg("图片格式不正确");
                }
                path = fdfsService.upload(file, suffix);
                System.out.println(path);
            }
        }else {
            return JSONResult.errorMsg("文件不能为空");
        }

        if (StringUtils.isNotBlank(path)){
            //由于浏览器可能存在缓存的情况，所以在这里，需要加上时间戳来保证更新后的图片可以及时刷新
            String finalUserFaceUrl=fileResource.getHost()+path;
           // 更新用户头像到数据库
            Users userResult = centerUserService.updateUserFace(userId, finalUserFaceUrl);

            //增加令牌token，会整合redis，分布式会话
            UsersVO usersVO = conventUsersVO(userResult);
            CookieUtils.setCookie(request,response,"user", JsonUtils.objectToJson(usersVO),true);

        }else {
            return JSONResult.errorMsg("上传头像失败");
        }

        return JSONResult.ok();
    }

}
